package com.example.speeddating.algorithm;

import java.util.*;

public class CosineSimilarity {
    
    // 计算向量的余弦相似度
    public static double cosineSimilarity(Map<String, Double> vector1, Map<String, Double> vector2) {
        double dotProduct = 0.0;
        double norm1 = 0.0;
        double norm2 = 0.0;
        
        // 计算向量点乘
        for (String key : vector1.keySet()) {
            if (vector2.containsKey(key)) {
                dotProduct += vector1.get(key) * vector2.get(key);
            }
            norm1 += Math.pow(vector1.get(key), 2);
        }
        
        for (String key : vector2.keySet()) {
            norm2 += Math.pow(vector2.get(key), 2);
        }
        
        // 计算余弦相似度
        double similarity = dotProduct / (Math.sqrt(norm1) * Math.sqrt(norm2));
        return similarity;
    }
    
    public static void main(String[] args) {
        // 用户向量
        Map<String, Double> userVector = new HashMap<>();
        userVector.put("tag1", 0.8);
        userVector.put("tag2", 0.2);
        userVector.put("tag3", 0.5);
        
        // 推荐文章向量
        Map<String, Double> articleVector = new HashMap<>();
        articleVector.put("tag1", 0.8);
        articleVector.put("tag2", 0.2);
        articleVector.put("tag3", 0.1);
        
        // 计算余弦相似度
        double similarity = cosineSimilarity(userVector, articleVector);
        System.out.println("Cosine similarity between user and article: " + similarity);
        
        // 设置标签权重
        Map<String, Double> tagWeights = new HashMap<>();
        tagWeights.put("tag1", 1.0);
        tagWeights.put("tag2", 1.0);
        tagWeights.put("tag3", 20.0);
        
        // 加权计算余弦相似度
        double weightedSimilarity = 0.0;
        for (String tag : userVector.keySet()) {
            if (articleVector.containsKey(tag) && tagWeights.containsKey(tag)) {
                weightedSimilarity += userVector.get(tag) * articleVector.get(tag) * tagWeights.get(tag);
            }
        }
        
        System.out.println("Weighted cosine similarity between user and article: " + weightedSimilarity);
    }
}